package com.wxj.book.service.impl;

import com.wxj.book.dao.ReceiverMapper;
import com.wxj.book.pojo.Receiver;
import com.wxj.book.pojo.User;
import com.wxj.book.service.ReceiverService;
import com.wxj.book.utils.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class ReceiverServiceImpl implements ReceiverService {

    @Autowired
    private ReceiverMapper receiverMapper;
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String form;
    @Value("${spring.mail.username}")
    private String email;

    /**
     * 查询领书记录
     *
     * @param stuNum
     * @return
     */
    @Override
    public Receiver getByStuNum(Integer stuNum) {
        return receiverMapper.getByStuNum(stuNum);
    }

    /**
     * 预约功能，写入数据库
     *
     * @param user
     * @return
     */
    @Override
    public int insert(User user) {
        Receiver receiver = new Receiver();
        String code = VerifyCodeUtil.createVerifyCode();
        // 发送邮件
        SimpleMailMessage mail = new SimpleMailMessage();
        // 由那个邮箱发出来
        mail.setFrom(form);
        // 发到那个邮箱去
        mail.setTo(user.getEmail());
        // 抄送到邮箱
        mail.setBcc(form);
        // 设置标题
        mail.setSubject("商师新教材管理系统预约码发送邮件");
        // 设置邮件内容
        mail.setText("尊敬的用户:" + user.getName() + "您好！您的学号：" + user.getStuNum() + "生成的预约码为：" + code + ", 如果非本人操作请忽略！");
        // 发送邮件
        try {
            mailSender.send(mail);
            // 预约码
            receiver.setCode(code);
            receiver.setStatus(1);
            receiver.setStuNum(user.getStuNum());
            return receiverMapper.insertSelective(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
